#!/usr/bin/env python
# -*- coding: utf-8 -*-
from fastapi import APIRouter, Query, Request, Form
from app.schemas.reranker_schema import FragmentRequest
from app.utils.response import success_response, error_response
from app.services.reranker_service import RerankerService
from app.utils.logging import log_message

# 内容重排序相关路由
router = APIRouter(tags=["reranker"], prefix="/reranker")


@router.get("/hello")
def get_prompt_list():
    """
    获取可用的 prompt 列表，支持版本参数
    """
    try:
        return success_response("reranker api")
    except Exception as e:
        return error_response(str(e))


@router.post("/fragment")
async def txt_reranker(
        request: Request,
        payload: FragmentRequest  # 直接使用Pydantic模型作为请求体
):
    """
    文本重排序接口

    Parameters:
    - **payload**: 包含以下字段的JSON请求体
      - query: 文本问题
      - texts: 待排序文本列表
    """
    try:
        # 对文本进行 rerank排序，返回排序后的结果， 使用模型bge-reranker-v2-m3
        # 调用排序服务
        reranker = RerankerService()
        results = await reranker.rerank_texts(
            query=payload.query,
            texts=payload.texts
        )

        processed_data = results
        return success_response(processed_data)

    except Exception as e:
        log_message(
            "reranker_error",
            {
                "version": payload.query,  # 从模型获取
                "type": payload.texts,
                "error": str(e)
            },
            "error"
        )
        return error_response(str(e))
